package com.xuzhiguang.lightnat.server.core.server.control.processor;

import com.xuzhiguang.lightnat.common.manager.ProxyChannelManager;
import com.xuzhiguang.lightnat.common.message.MessageProcessor;
import com.xuzhiguang.lightnat.common.message.NatMessage;
import com.xuzhiguang.lightnat.common.message.control.ConnectResponse;
import com.xuzhiguang.lightnat.server.core.client.NatClientService;
import com.xuzhiguang.lightnat.server.core.client.ProxyTypeEnum;
import com.xuzhiguang.lightnat.server.core.server.proxy.refuse.RefuseStrategyFactory;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ConnectResponseProcessor implements MessageProcessor {

    private final NatClientService natClientService;

    public ConnectResponseProcessor(NatClientService natClientService) {
        this.natClientService = natClientService;
    }

    @Override
    public void process(ChannelHandlerContext ctx, NatMessage natMessage) {

        log.debug("control ConnectResponseProcessor. channel:{}", ctx.channel());

        if (natMessage.getBody() instanceof ConnectResponse) {
            ConnectResponse response = (ConnectResponse) natMessage.getBody();
            if (!response.getSuccess()) {

                // 连接失败. 返回错误信息
                log.warn("client error:{}", response.getErrMsg());
                Channel proxyChannel = ProxyChannelManager.get(response.getSessionId());
                if (proxyChannel != null) {
                    ProxyTypeEnum proxyTypeEnum = natClientService.getNatProxy(ProxyChannelManager.getProxyId(proxyChannel)).getProxyType();
                    RefuseStrategyFactory.getStrategy(proxyTypeEnum).refuse(proxyChannel, response.getErrMsg());
                }
            }
        }
    }
}
